package com.ctbri.vSearch.frame;


import com.ctbri.vSearch.util.PropUtil;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by xuexi on 2017/4/24.
 */
public class RedisPooledConnection {

    RedisPool redisPool = null;
    JedisPool jedisPool = null;

    private static final String IP = PropUtil.getValue("redis.url");
    private static final int PORT = Integer.parseInt(PropUtil.getValue("redis.port"));

    private  Logger log = Logger.getLogger(getClass());

    public RedisPooledConnection(){
        initPool();
    }

    /**
     * 初始化连接池
     */
    public void initPool(){
        this.redisPool = new RedisPool();
        if(jedisPool == null) {
            this.jedisPool = redisPool.getPool(IP, PORT);
        }
        log.info("初始化Redis连接池");
    }

    /**
     * 创建一个新的链接
     * @return
     */
    public Jedis getClient(){
        Jedis client = null;
        try {
            if(jedisPool != null){
                client = jedisPool.getResource();
                log.info("成功获取Redis连接，目前活跃连接数为 " + jedisPool.getNumActive());
            }
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(client);
            log.error("获取Redis连接失败");
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 返还到连接池
     *
     * @param client
     */
    public void returnResource(Jedis client) {
        if (client != null) {
            this.jedisPool.returnResource(client);
        }
        log.info("成功返还Redis连接，目前空闲连接数为 " + jedisPool.getNumIdle());
    }

}
